$(document).ready(function () {
    $('.i-checks').iCheck({
        checkboxClass: 'icheckbox_square-green',
        radioClass: 'iradio_square-green',
    });
});

var _taskid = null;
//日期范围限制
var start = {
    elem: '#start',
    format: 'YYYY-MM-DD',
    min: '2017-06-01', //设定最小日期为当前日期
    max: laydate.now(), //最大日期
    istime: true,
    istoday: false,
    choose: function (datas) {
        end.min = datas; //开始日选好后，重置结束日的最小日期
        end.start = datas; //将结束日的初始值设定为开始日
    }
};
var end = {
    elem: '#end',
    format: 'YYYY-MM-DD',
    min: '2017-06-01',
    max: laydate.now(),
    istime: true,
    istoday: false,
    choose: function (datas) {
        start.max = datas; //结束日选好后，重置开始日的最大日期
    }
};
laydate(start);
laydate(end);


var slider = document.getElementById('slider');
//var task_loading = Ladda.create( document.getElementById('task_submit') );
//var data_loading = Ladda.create(document.getElementById('getData'));
var task_loading = $("#task_submit").ladda();
var data_loading = $("#getData").ladda();

noUiSlider.create(slider, {
    start: [30, 40],
    connect: true,
    tooltips: true,
    step: 1,
        format: wNumb({
        decimals: 0
    }),
    range: {
        'min': 18,
        'max': 70
    }
});
var t_data = [];
var visit_data = [];
var step_data = [];
var name_data=new Array();
var value_data=new Array();

$(function() {
    $("#getData").click(function(){
        $("#f2").attr("target","rfFrame");
        //var index = layer.load(1);
        //data_loading.start();
        data_loading.ladda('start');
       $.ajax({
           dataType : 'json',
           type : 'get',
           //url : 'http://localhost:8080/getData/'+_taskid,
           url : 'http://localhost:8080/getData/25',
           success : function(result) {
               if (result != null){
                   var session_count = result.data.session_count;
                   t_data = [];
                   visit_data = [];
                   step_data = [];
                   name_data=new Array();
                   value_data=new Array();

                   $.each(result.data,function(key,val){
                       if(key.split('_')[0] == 't'){
                           t_data.push({name:key.split('_')[1]+'~'+key.split('_')[2],value:val});
                       }else if(key.split('_')[0] == 'visit'){
                           var visit_name ;
                           var visit_value ;
                           if(key.split('_').length == 5){
                               visit_name = key.split('_')[2] + '-' + key.split('_')[3];
                               visit_value = parseInt(val * session_count);

                           }else if(key.split('_').length == 4){
                               visit_name = key.split('_')[2];
                               visit_value = parseInt(val * session_count);
                           }
                           visit_data.push({name:visit_name,value:visit_value});
                       }else if(key.split('_')[0] == 'step'){
                           var step_name ;
                           var step_value ;
                           if(key.split('_').length == 5){
                               step_name = key.split('_')[2] + '-' + key.split('_')[3];
                               step_value = parseInt(val * session_count);
                           }else if(key.split('_').length == 4){
                               step_name = key.split('_')[2];
                               step_value = parseInt(val * session_count);
                           }
                           step_data.push({name:step_name,value:step_value});
                       }else{
                           if (key == "beijing" && parseInt(val) != 0){
                               name_data.push("北京");
                               value_data.push(parseInt(val));
                           }else if(key == "shanghai" && parseInt(val) != 0){
                               name_data.push("上海");
                               value_data.push(parseInt(val));
                           }else if(key == "guangzhou" && parseInt(val) != 0){
                               name_data.push("广州");
                               value_data.push(parseInt(val));
                           }else if(key == "shenzhen" && parseInt(val) != 0){
                               name_data.push("深圳");
                               value_data.push(parseInt(val));
                           }else if(key == "hangzhou" && parseInt(val) != 0){
                               name_data.push("杭州");
                               value_data.push(parseInt(val));
                           }else if(key == "nanjing" && parseInt(val) != 0){
                               name_data.push("南京");
                               value_data.push(parseInt(val));
                           }
                       }
                   });

                   var timeChart = echarts.init(document.getElementById("session-time-chart"));
                   var lengthChart = echarts.init(document.getElementById("session-length-chart"));
                   var cityChart = echarts.init(document.getElementById("city-chart"));
                   var tChart = echarts.init(document.getElementById("time-chart"));

                   length_option = {
                       title : {
                           text: 'session访问步长分布',
                           x:'center'
                       },
                       tooltip : {
                           trigger: 'item',
                           formatter: "{a} <br/>{b} : {c} ({d}%)"
                       },
                       legend: {
                           orient : 'vertical',
                           x : 'left',
                           data:['1-3','4-6','7-9','10-30','30-60','60']
                       },
                       calculable : true,
                       series : [
                           {
                               name:'访问步长',
                               type:'pie',
                               radius : '55%',
                               center: ['50%', '60%'],
                               data: step_data
                           }
                       ]
                   };
                   time_option = {
                       title : {
                           text: 'session访问时长分布',
                           x:'center'
                       },
                       tooltip : {
                           trigger: 'item',
                           formatter: "{a} <br/>{b} : {c} ({d}%)"
                       },
                       legend: {
                           orient : 'vertical',
                           x : 'left',
                           data:['1s-3s','4s-6s','7s-9s','10s-30s','30s-60s','1m-3m','3m-10m','10m-30m','30m']
                       },
                       calculable : true,
                       series : [
                           {
                               name:'访问时长',
                               type:'pie',
                               radius : '55%',
                               center: ['50%', '60%'],
                               data: visit_data
                           }
                       ]
                   };


                   t_option = {
                       title : {
                           text: '用户访问时间分布',
                           x:'center'
                       },
                       tooltip: {
                           trigger: 'item',
                           position: ['48.5%', '49.2%'],
                           backgroundColor: 'rgba(50,50,50,0)',
                           textStyle : {
                               color: 'yellow',
                               fontWeight: 'bold'
                           },
                           formatter: "{d}%"
                       },
                       series : [
                           {
                               name: '访问时间',
                               type: 'pie',
                               radius : ['5%', '70%'],
                               roseType: 'area',
                               color:['#3fa7dc'],
                               data:t_data,
                               labelLine: {
                                   normal: {
                                       show: false
                                   }
                               },
                               label: {
                                   normal: {
                                       show: false
                                   }
                               },
                               itemStyle: {
                                   normal: {
                                       shadowBlur: 10,
                                       shadowOffsetX: 0,
                                       shadowColor: 'rgba(0, 0, 0, 0.5)'
                                   },
                                   emphasis: {
                                       shadowBlur: 10,
                                       shadowOffsetX: 0,
                                       shadowColor: 'rgba(0, 0, 0, 0.5)'
                                   }
                               }
                           },
                           {
                               name: '',
                               type: 'gauge',
                               min: 0,
                               max: 24,
                               startAngle: 90,
                               endAngle: 449.9,
                               radius: '82%',
                               splitNumber: 24,
                               clockwise: false,
                               animation: false,
                               detail: {
                                   formatter: '{value}',
                                   textStyle: {
                                       color: '#63869e'
                                   }
                               },
                               detail:{
                                   show: false
                               },
                               axisTick: {
                                   show: false
                               },
                               axisLine: {
                                   lineStyle: {
                                       color: [
                                           [0.25, '#63869e'],
                                           [0.75, '#ffffff'],
                                           [1, '#63869e']
                                       ],
                                       width: '40%',
                                       shadowColor: '#0d4b81', //默认透明
                                       shadowBlur: 40,
                                       opacity: 1
                                   }
                               },
                               splitLine: {
                                   length: 5,
                                   lineStyle: {
                                       color: '#ffffff',
                                       width: 2
                                   }
                               },
                               axisLabel: {
                                   formatter: function(v){
                                       return v?v:'';
                                   },
                                   textStyle: {
                                       color: "red",
                                       fontWeight: 700
                                   }
                               },
                               itemStyle: {
                                   normal: {
                                       color: 'green',
                                       width: 2
                                   }
                               }
                           },
                           {
                               name: '',
                               type: 'gauge',
                               min: 0,
                               max: 24,
                               startAngle: 90,
                               endAngle: 449.9,
                               radius: '72%',
                               splitNumber: 24,
                               clockwise: false,
                               animation: false,
                               detail: {
                                   formatter: '{value}',
                                   textStyle: {
                                       color: '#63869e'
                                   }
                               },
                               detail:{
                                   show: false
                               },
                               axisTick: {
                                   show: false
                               },
                               axisLine: {
                                   lineStyle: {
                                       color: [
                                           [1, '#E8E8E8']
                                       ],
                                       width: '10%',
                                       opacity:0.8
                                   }
                               },
                               splitLine: {
                                   show:true,
                                   length: '92%',
                                   lineStyle: {
                                       color: 'grey',
                                       width: '1'
                                   }
                               },
                               axisLabel: {
                                   show:false,
                                   formatter: function(v){
                                       return v?v:'';
                                   },
                                   textStyle: {
                                       color: "#fb5310",
                                       fontWeight: 700
                                   }
                               },
                               itemStyle: {
                                   normal: {
                                       color: 'green',
                                       width: 2,
                                       borderWidth: 3,
                                   }
                               }
                           }
                       ]
                   };




                   city_option = {
                       title : {
                           text: 'session访问地区分布',
                           x:'center'
                       },
                       color: ['#3398DB'],
                       tooltip : {
                           trigger: 'axis',
                           axisPointer : {            // 坐标轴指示器，坐标轴触发有效
                               type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                           }
                       },
                       grid: {
                           left: '3%',
                           right: '4%',
                           bottom: '3%',
                           containLabel: true
                       },
                       xAxis : [
                           {
                               type : 'category',
                               data : name_data,
                               axisTick: {
                                   alignWithLabel: true
                               }
                           }
                       ],
                       yAxis : [
                           {
                               type : 'value'
                           }
                       ],
                       series : [
                           {
                               name:'访问session数量',
                               type:'bar',
                               barWidth: '60%',
                               data: value_data
                           }
                       ]
                   };

                   timeChart.setOption(time_option);
                   lengthChart.setOption(length_option);
                   cityChart.setOption(city_option);
                   tChart.setOption(t_option);
                   $(window).resize(tChart.resize);
                   $(window).resize(lengthChart.resize);
                   $(window).resize(timeChart.resize);
                   $(window).resize(cityChart.resize);
                   document.getElementById("graph_view").style.display="";
                   document.getElementById("graph_view2").style.display="";
                   //document.getElementById("graph_view3").style.display="";
                   //layer.close(index);
                   //data_loading.stop();
                   data_loading.ladda('stop');
               }
           }

       });
    });

    $("#task_submit").click(function() {
        $("#f2").attr("target","rfFrame");
        // var params =""
        var taskName = $("#taskName").val();
        var startDate = $("#start").val();
        var endDate = $("#end").val();
        var startAge = slider.noUiSlider.get()[0];
        var endAge = slider.noUiSlider.get()[1];
        var city = "";
        var sex = $("#sex").val();
        var str =""
        $("input[name='city']:checkbox").each(function(){
            if(true == $(this).is(':checked')){
                str+=$(this).val()+",";
            }
        });
        if(str.substr(str.length-1)== ','){
            city = str.substr(0,str.length-1);
        }
        // if(city != ""){
        //     params = taskName + "&" +startDate + "&" +endDate + "&" + startAge + "&" + endAge + "&" + city + "&" + sex ;
        // }else {
        //     params = taskName + "&" +startDate + "&" +endDate + "&" + startAge + "&" + endAge + "&" + sex ;
        // }

        //var index = layer.load(1);
        //task_loading.start();
        task_loading.ladda('start');
        $.ajax({
            data : {
                taskName: taskName,
                startDate: startDate,
                endDate: endDate,
                startAge: startAge,
                endAge: endAge,
                city: city,
                sex: sex
            },
            dataType : 'json',
            type : 'post',
            url : 'http://localhost:8080/save',
            success : function(result) {
                if (result != null ) {
                    //layer.close(index);
                    //task_loading.stop();
                    task_loading.ladda('stop');
                    layer.msg("任务完成！", {
                        shade : 0.3,
                        time : 1500
                    }, function() {
                        _taskid = result.data.taskid;
                    });
                } else {
                    layer.msg("任务失败！");
                }
            }
        })
    })
});
